<?php

namespace App\Repositories\Admin;

use App\BaseRepository;
use App\Model\Role;
use App\Model\UserRole;
use Illuminate\Validation\Rule;

class AdminRepository extends BaseRepository
{
    //模型名称
    protected $modelName = "App\User";

    protected function checkAuth($action)
    {
        if ($this->isSuper() != 'super') {
            $this->error = $this->noPower();
            return false;
        }
        return parent::checkAuth($action);
    }

    protected function query()
    {
        return $this->model()->whereIn('userType',['admin','editor']);
    }

    protected function commonRules()
    {
        $rules = [
            'name' => 'required',
            'password' => 'required|confirmed',
            'userType' => 'required|in:admin,editor'
        ];

        if ($this->request->input('ip_min')){
            $rules['ip_min'] = 'ipv4';
        }

        if ($this->request->input('ip_max')){
            $rules['ip_max'] = 'ipv4';
        }

        return $rules;
    }

    //保存的验证规则
    protected function storeRules()
    {
        return [
            'account' => [
                'required',
                Rule::unique('t_user','account')->whereNull('deleted_at')
            ],
        ];
    }

    //更新的验证规则
    protected function updateRules($id)
    {
        return [
            'account' => [
                'required',
                Rule::unique('t_user','account')->ignore($id)->whereNull('deleted_at')
            ],
        ];
    }

    protected function getStoreFillData()
    {
        $data = $this->removeNullFromArray($this->request->only('name','account','password','ip_min','ip_max','userType'));
        $data['password'] = bcrypt($data['password']);
        return $data;
    }

    protected function getUpdateFillData()
    {
        $data = $this->removeNullFromArray($this->request->only('name','account','password','ip_min','ip_max'));
        if(isset($data['password']) && $data['password']) {
            $data['password'] = bcrypt($data['password']);
        }
        return $data;
    }

    protected function afterStore($model)
    {
        $role = Role::where('code','=',$this->request->input('userType'))->first();
        if($role) {
            $m= new UserRole();
            $m->user_id = $model->id;
            $m->role_id = $role->id;
            $m->save();
        }
    }
}